package cn.cupk.logsystem.controller;

import cn.cupk.logsystem.pojo.Administrator;
import cn.cupk.logsystem.result.Result;
import cn.cupk.logsystem.service.AdministratorService;
import cn.cupk.logsystem.utils.JwtUtil;
import cn.cupk.logsystem.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdministratorController {

    @Autowired
    private AdministratorService administratorService;

    @PostMapping("/register")
    public Result<String> register(@RequestParam String username, @RequestParam String password) {

        //校验
        if (administratorService.findAdminByUsername(username) != null) {
            return Result.error("用户名已存在");
        }

        //添加用户
        administratorService.insertAdministrator(username, password);

        return Result.success("注册成功");
    }


    @PostMapping("/login")
    public Result<String> login(@RequestParam String username, @RequestParam String password) {
        //校验

        Administrator admin = administratorService.findAdminByUsername(username);
        if (admin == null) {
            return Result.error("用户名不存在");
        }

        if (Md5Util.getMD5String(password).equals(admin.getPassword())){
            //登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", admin.getId());
            claims.put("username", admin.getUsername());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }
}
